/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

#include "bhtpdvpls_structs.h"
#include "pslsimfunc.h"


int main(int argc, char *argv[])
{
    struct sockaddr_in serv_addr, cli_addr;

    if (argc < 2) {
	fprintf(stderr,"ERROR, no port provided\n");
	exit(1);
    }

    int16_t portno = atoi(argv[1]);
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
	error("ERROR opening socket");

    memset((void *)&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family 	= AF_INET;
    serv_addr.sin_addr.s_addr 	= INADDR_ANY;
    serv_addr.sin_port 		= htons(portno);
    if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
	error("ERROR on binding");
    listen(sockfd,5);
    
    int thisRobotID = -1; // am anfang weiß der bot noch nicht seine id,
    while(1)
    {
	printf("Wating to connect\n");
	int clilen = sizeof(cli_addr);
	int plssock = accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t*)(&clilen));
	if (plssock < 0)
	    error("ERROR on accept");
	else
	    printf("Connected\n");

       while(1)
       {
         ComandPkg command;
         int n  = readin(plssock, (char*)&command,  sizeof(ComandPkg));
	 if(n == 0)
	 {
	    printf("Disconnected\n");
	    break;
	 }

	ObjektListe objekte;
	switch(command.cmd)
	{
	    case STATUS_REQUEST:
		thisRobotID = command.kord.objektId; // damit der bot weiß welche ID er hat in der ObjektListe	
		printf("recv %s robotID is %04d\n", commandToStr[command.cmd], thisRobotID);

		sendCmdPkgEx(plssock, STATUS_ANSWER, thisRobotID, 1, 1, 90); 
		// hier müssen die 1, 1, 90 durch die position ersetzt werden
	    break;
	    
	    case OBJECTS_UPDATE:
		printf("recv %s\n", commandToStr[command.cmd]);
		n  = readin(plssock, (char*)&objekte,  sizeof(ObjektListe));
		if(n == 0)
		{
		    printf("Disconnected\n");
		    break;
		}
	    break;
	    
	    case DESTINATION_COMMAND:
	      	printf("recv %s ", commandToStr[command.cmd]);
		printf("id%04d:%04dx:%04dy:%04dphi\n", 
			command.kord.objektId, command.kord.xkordinate_mm, command.kord.ykordinate_mm, command.kord.theta_grad);
	    break;
	    
	    case STOP_COMMAND:
		printf("recv %s\n", commandToStr[command.cmd]);
	    break;
	    
	    case START_COMMAND:
		printf("recv %s\n", commandToStr[command.cmd]);
	    break;
	    
	    default:
	      //TODO: Fehler abfangen
	    break;
	}
       }
     }

     close(sockfd);
     return 0;
}
